package org.wiztools.smmock;

import java.io.IOException;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author subwiz
 */
public class SMLoginServlet extends HttpServlet {

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        final String targetParameterName = SMProperties.get("targetParameterName");
        final String target = request.getParameter(targetParameterName);
        if(target == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Parameter NOT provided: " + targetParameterName);
        }
        else {
            final String cookieKey = SMProperties.get("smSessionCookieName");
            Cookie cookie = new Cookie(cookieKey, UUID.randomUUID().toString());
            cookie.setDomain(SMProperties.get("smCookieDomain"));
            cookie.setPath(SMProperties.get("smCookiePath"));
            response.addCookie(cookie);
            response.sendRedirect(target);
        }
    }
}
